package org.jetlinks.community.mstn.term;

import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.EmptySqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MstnTenantDimensionTermBuilder extends AbstractTermFragmentBuilder {

    public static final String tenantDimension = "mstn-tenant-dimension";

    public MstnTenantDimensionTermBuilder() {
        super(tenantDimension, "查询租户下权限");
    }



    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata rdbColumnMetadata, Term term) {
        List<Object> values = this.convertList(rdbColumnMetadata, term);
        if (values.isEmpty()) {
            return EmptySqlFragments.INSTANCE;
        }
        PrepareSqlFragments fragments = PrepareSqlFragments.of();
        List<String> options = term.getOptions();
        if (options.size() > 0) {
            Object value = term.getValue();
            String supportId = options.get(0);
            String type = options.get(1);

            //自己创建
            if ("creator".equals(supportId)){
                fragments.addSql( rdbColumnMetadata.getOwner().getAlias() + ".creator_id" + " = ?").addParameter( value );
            } else if ("org".equals(supportId)) {//机构下
                fragments.addSql( rdbColumnMetadata.getOwner().getAlias() + ".path like (select concat(path, '-%')  from s_organization s where s.id  = ?)").addParameter( value );
            } else if ("org-include-children".equals(supportId)) { //所在组织及下级组织
                fragments.addSql( rdbColumnMetadata.getOwner().getAlias() + ".path like (select concat(path, '%')  from s_organization s where s.id  = ?)").addParameter( value );
            } else { //全部数据
                return EmptySqlFragments.INSTANCE;
            }

        }
        return fragments;
    }
}
